// index.js
// 获取应用实例
const app = getApp()
// import socket from '../../utils/websocket.js'
import api from '../../utils/api.js'
import util from '../../utils/util.js'
import Dialog from '@vant/weapp/dialog/dialog';

// 引入腾讯位置服务
var QQMapWX = require('../../lib/qqmap-wx-jssdk.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: 'U5VBZ-N54W3-TOW3X-YOB2G-LHJGT-G6FC5'
});
const chooseLocation = requirePlugin('chooseLocation');
//定时获取用户的经纬度


Page({
    data: {
        userInfo: null, //用户信息
        // 用户的维度
        latitude: "",
        longitude: "",
        startAddr: "",
        // 目的地
        endAdr: "",
        height: null, //状态栏的高度
        // 代驾人的点位分布
        markers: [],
        // 地址
        address: "",
        // 地点名称
        startXxAddr: "",
        endXxAddr: "",
        endTip: "您要去哪里？",
        locationName: "",
        isShow: true, //控制订单的出现
        isTop: true, //控制订单页面的折叠
        isHas: false, //控制价格的出现
        isedit: false,
        endLat: '',
        show: false, //控制loading弹窗的出现
        endLng: '',
        orderId: null, // 用户下单后返回的id
        isEnd: true, //控制支付成功页面的出现
        isStart: false, //控制开始出发按钮的出现
        isWc: false, //控制完成订单按钮的出现
        isBackMsg: false, //监听是否有消息返回
        isPay: false, //控制支付按钮的出现
        isTrue: false, //改变满意按钮颜色
        isFit: false, //查看费用详情
        isLogin: false,
        price: 0, //起步价
        forecastPri: 0, //预估价
        st_address: null, //起始地址
        e_address: null, //结束地址
        st_time: null, //起始时间
        value: 5, //评分
        shopId: null, //商家id
        // trader_id
        djName: '', //代驾姓名
        djMobile: '', //代驾手机
        djTx: '', //代驾头像
        orderData: {},
        maintenanceData: {},
        countDownTime: '00:00',
        timeNum: 10, //倒数秒数
        isCount: false, //是否显示等待时间内的弹窗
        payOrderData: {}, //订单结束后的支付后数据
        sceneData: null //扫码的内容
    },
    evaChange(e) {
        this.setData({
            value: e.detail
        })
    },
    agress(e) {
        // 评价
        // http://dageda.api.hjdz.ltd/userdjorder/commentorder
        var that = this;
        var apis = api.api;
        var url = apis.host + 'userdjorder/commentorder';
        if (e.currentTarget.dataset.value == "yes") {
            var data = {
                id: that.data.orderData.id,
                /* 是	string	订单ID */
                store: '满意',
                /* 是	string	评分 */
                comment: that.data.value.toString(),
                /* 是	string	评价内容 */
            }
            apis.request(url, data, 'POST').then(function (res) {
                if (res.code == 200) {
                    wx.showToast({
                        title: '评分成功',
                        icon: 'success'
                    })
                    that.setData({
                        isEnd: false,
                        orderData: {}
                    })
                    that.clearLocal()
                } else {
                    wx.showToast({
                        title: '评分失败，请重试！',
                        icon: 'none'
                    })
                }
            })
        } else if (e.currentTarget.dataset.value == "jump") {
            var data = {
                id: that.data.orderData.id,
                /* 是	string	订单ID */
                store: '满意',
                /* 是	string	评分 */
                comment: that.data.value.toString(),
                /* 是	string	评价内容 */
            }
            apis.request(url, data, 'POST').then(function (res) {
                if (res.code == 200) {
                    wx.showToast({
                        title: '评分成功',
                        icon: 'success'
                    })
                    that.setData({
                        isEnd: false,
                        orderData: {}
                    })

                    that.clearLocal()
                } else {
                    wx.showToast({
                        title: '评分失败，请重试！',
                        icon: 'none'
                    })
                }
            })
        } else {
            var data = {
                id: that.data.orderData.id,
                /* 是	string	订单ID */
                store: '不满意',
                /* 是	string	评分 */
                comment: that.data.value.toString(),
                /* 是	string	评价内容 */
            }
            apis.request(url, data, 'POST').then(function (res) {
                if (res.code == 200) {
                    wx.showToast({
                        title: '评分成功',
                        icon: 'success'
                    })
                    that.setData({
                        isEnd: false,
                        orderData: {}
                    })
                    that.clearLocal()
                } else {
                    wx.showToast({
                        title: '评分失败，请重试！',
                        icon: 'none'
                    })
                }
            })
        }

    },
    clearLocal() {
        //评价完后清除地址缓存
        var that = this;
        wx.removeStorage({
            key: 'myLocal'
        })
        wx.removeStorage({
            key: 'finalLocal'
        })
        that.getData()
    },
    closeIcon() {
        //隐藏评价完的窗口
        this.setData({
            isEnd: true
        })
    },
    checkFit() {
        // 查看费用详情
        this.setData({
            isFit: true,
        })
    },
    toCall() {
        // 报警
        wx.makePhoneCall({
            phoneNumber: '110', //仅为示例，并非真实的电话号码
            success: function (res) {},
            fail: function (res) {}
        })
    },
    toShare() {
        // 分享
    },
    toKf() {
        //微信客服
    },
    startNow() {
        // 用户确认订单，订单开始
        // http://dageda.api.hjdz.ltd/userdjorder/ordersure
        // userdjorder/changeStatus
        var that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认出发？',
            success: function (res) {
                let apis = api.api;
                let url = apis.host + 'userdjorder/changeStatus';
                let data = {
                    oid: that.data.orderId /* 是	string	订单ID */
                };
                apis.request(url, data, 'POST').then(function (res) {
                    wx.showToast({
                        title: '已确认出发',
                        icon: 'success'
                    })
                    // console.log('订单信息', res)
                }).catch(function (res) {
                    // console.log('订单开始失败', res)
                })
            },
            fail: function (res) {
                wx.showToast({
                    title: '您没确认',
                    icon: 'none'
                })
            }
        })
    },
    endNow() {
        // 订单完成
        var that = this;
        wx.showModal({
            title: '提示',
            content: '确认到达目的地？',
            success: function (res) {
                let apis = api.api;
                let url = apis.host + 'userdjorder/ordersurepay';
                let data = {
                    id: that.data.orderData.id /* 是	string	订单ID */
                };
                apis.request(url, data, 'POST').then(function (res) {
                    let data = res.data.pay;
                    if (res.code == 200) {
                        if (res.data.pay) {
                            wx.requestPayment({
                                timeStamp: data.timeStamp.toString(),
                                nonceStr: data.nonce_str.toString(),
                                package: 'prepay_id=' + data.prepay_id
                                    .toString(),
                                signType: 'MD5',
                                paySign: data.paySign.toString(),
                                success(res) {
                                    wx.showLoading({
                                        title: '正在验证'
                                    })
                                    setTimeout(function () {
                                        wx.hideLoading()
                                    }, 5000)
                                    setTimeout(function () {
                                        that.setData({
                                            isShow: true
                                        })
                                    }, 5000)
                                },
                                fail(res) {
                                    wx.showToast({
                                        title: '支付失败，请重试！！',
                                        icon: 'none'
                                    })
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '订单完成',
                                icon: 'success',
                                success() {
                                    that.setData({
                                        isShow: true
                                    })
                                }
                            })
                        }
                    } else {
                        // console.log('订单失败', res.msg)
                    }
                }).catch(function (res) {
                    // console.log('订单开始失败', res)
                })
            },
            fail: function (res) {
                wx.showToast({
                    title: '您没确认',
                    icon: 'none'
                })
            }
        })
    },
    goChat() {
        this.setData({
            isBackMsg: false
        })
        wx.navigateTo({
            url: '/pages/chat/chat'
        })
    },
    call() {
        var that = this;
        // index/call
        var apis = api.api;
        var url = apis.host + 'index/call';
        var data = {
            to_user: that.data.orderData.dj_id
        }
        apis.request(url, data, 'POST').then(function (res) {
            if (res.code == 200) {
                if (res.data.type == 1) {
                    wx.makePhoneCall({
                        phoneNumber: res.data.phone, //仅为示例，并非真实的电话号码
                        success: function (res) {
                            wx.showToast({
                                title: '正在呼叫',
                                icon: 'success'
                            })
                        },
                        fail: function (res) {
                            wx.showToast({
                                title: '呼叫失败',
                                icon: 'none'
                            })
                        }
                    })
                }
            } else {
                wx.showToast({
                    title: '等待电话回拨',
                    icon: 'loading'
                })
            }
        })
    },
    onShareAppMessage() {
        const promise = new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    title: '这个小程序太好用了，推荐你使用'
                })
            }, 2000)
        })
        return {
            title: '这个小程序太好用了，推荐你使用',
        }
    },
    getServerConfig() {
        var that = this;
        let apis = api.api;
        let url = apis.host + 'sys/getServerConfig';
        let data = {};
        apis.request(url, data, 'POST').then(function (res) {
            if (res.code == 200) {
                that.setData({
                    maintenanceData: res.data
                })
            }
        })
    },
    countDownTime(second) {
        //设置订单开始时倒计时的时间
        //有参数的时候是设置秒数倒计时,没参数时是用于分钟倒计时
        let date = new Date()
        let id = wx.getStorageSync('userAllInfo').id
        if (second) {
            let endSecond = date.setMinutes(date.getSeconds() + second)
            endSecond = parseInt(endSecond / 1000)
            wx.setStorageSync('order_time_second_' + id, endSecond)
        } else {
            let endTime = date.setMinutes(date.getMinutes() + 5)
            endTime = parseInt(endTime / 1000)
            wx.setStorageSync('order_time_' + id, endTime)
        }

    },
    countDown() {
        //开启定时器
        let date = new Date()
        let that = this
        let id = wx.getStorageSync('userAllInfo').id
        let now = date.getTime();
        now = parseInt(now / 1000)
        let endTime = wx.getStorageSync('order_time_' + id)
        var lostTime = endTime - now
        let formatTime = this.getFormat(lostTime);
        let countDownTime = `${formatTime.mm}:${formatTime.ss}`;
        that.setData({
            countDownTime: countDownTime
        })
        var stopTime = setTimeout(function () {
            if (lostTime <= 0) {
                clearTimeout(stopTime)
                if (JSON.stringify(that.data.orderData) === "{}") {
                    return false
                } else {
                    if (endTime) {
                        that.setData({
                            isCount: true
                        })
                        // var num = 10
                        // var count = setInterval(function() {
                        // 	if (num <= 0) clearInterval(count)
                        // 	num--
                        // 	that.setData({
                        // 		timeNum: num
                        // 	})
                        // }, 1000)
                        var timeOut = setTimeout(function () {
                            if (!wx.getStorageSync('isClose')) {
                                that.cancels()
                                wx.setStorageSync('isClose', false)
                            }
                            clearTimeout(timeOut)
                            that.setData({
                                isCount: false
                            })
                            wx.setStorageSync('isClose', false)
                        }, 10000)
                    }
                    wx.removeStorage({
                        key: 'order_time_' + id,
                        success(res) {}
                    })
                }
            } else {
                that.countDown()
            }
        }, 1000)
    },
    removeCountDown() {
        // 移除定时器
        let id = wx.getStorageSync('userAllInfo').id
        wx.removeStorage({
            key: 'order_time_' + id,
            success(res) {}
        })
    },
    // 格式化时间
    getFormat: function (msec) {
        let ss = parseInt(msec);
        let mm = 0;
        if (ss > 60) {
            mm = parseInt(ss / 60);
            ss = parseInt(ss % 60);
            if (mm > 60) {
                mm = parseInt(mm % 60);
            }
        }
        ss = ss > 9 ? ss : `0${ss}`;
        mm = mm > 9 ? mm : `0${mm}`;
        return {
            ss,
            mm,
        };
    },
    cancelBtn(e) {
        //点击取消时子组件调用的方法
        wx.setStorageSync('isClose', false)
        this.setData({
            isCount: false
        })
        this.cancels()
    },
    confirmBtn() {
        //点击确定时子组件调用的方法
        app.sendMessage('update_task_status', {
            id: this.data.orderData.id
        })
        wx.setStorageSync('isClose', true)
        this.setData({
            isCount: false
        })
        this.countDownTime()
        this.countDown()
    },
    onShow: function () {
        try {
            var that = this;
            let apis = api.api;
            let data = {};
            that.getServerConfig()
            var userInfo = app.globalData.userAllInfo;
            var maintenance = wx.getStorageSync('maintenance')
            var isLogin = false;
            if (wx.getStorageSync('session')) {
                isLogin = true;
            }
            that.setData({
                userInfo: userInfo,
                listData: that.data.pingData,
                maintenanceData: maintenance,
                isLogin: isLogin
            })
            if (wx.getStorageSync('order_time_' + wx.getStorageSync('userAllInfo').id)) {
                this.countDown()
            }
            var lng = wx.getStorageSync('myLocal').longitude;
            var lat = wx.getStorageSync('myLocal').latitude;
            app.messageEvent = function (event, data) {
                /**
                 * @var string event	事件名称
                 * @var object data	返回的数据
                 */
                switch (event) {
                    case "order_status":
                        //监听订单状态
                        if (Number(data.status) >= 5 && Number(data.status) !== 8) {
                            wx.hideLoading()
                            that.setData({
                                price: data.price,
                                orderData: data,
                                payOrderData: data
                            })
                        } else {
                            that.setData({
                                price: data.pre_price
                            })
                        }
                        if (Number(data.dj_id) === Number(that.data.orderData.dj_id)) {
                            data.alltime = util.formatStoM(data.alltime)
                            if (data.sj_path) {
                                data.sj_path.juli = parseFloat(data.sj_path.juli).toFixed(2)
                            }
                            that.setData({
                                orderData: data,
                                orderId: data.id,
                            })
                        } else {
                            if (Number(data.dj_id) === 0) {
                                if (wx.getStorageSync('order_time_' + wx.getStorageSync('userAllInfo')
                                        .id)) {
                                    that.removeCountDown()
                                }
                                that.countDownTime()
                                that.countDown()
                                that.setData({
                                    orderId: data.id,
                                    djName: '',
                                    djMoblie: "",
                                    djTx: "",
                                })
                            } else {
                                app.getUserInfo(data.dj_id, function (res) {
                                    if (res) {
                                        that.removeCountDown()
                                        that.setData({
                                            orderId: data.id,
                                            djName: res.username,
                                            djMoblie: res.moblie,
                                            djTx: res.avatar
                                        })
                                    }
                                })
                            }
                            data.alltime = util.formatStoM(data.alltime)
                            if (data.sj_path) {
                                data.sj_path.juli = parseFloat(data.sj_path.juli).toFixed(2)
                            }
                            that.setData({
                                orderData: data,
                                orderId: data.id
                            })
                        }
                        return true;
                        break;
                    case "im":
                        //接收当前消息返回的消息ID
                        that.setData({
                            isBackMsg: true,
                        })
                        break;
                    case "server_content_update":
                        // dj_app_close_content: "系统正在维护，将在1天后开放。。。aaa，是飒飒试试"
                        // dj_app_close_title: "系统正在维护中"
                        // dj_app_open: "1"
                        // user_xcx_close_content: "系统正在维护，将在1天后开放。。。aaa，是飒飒试试"
                        // user_xcx_close_title: "系统正在维护中"
                        // user_xcx_open: "0"
                        // __token__: ""
                        wx.setStorageSync('maintenance', data)
                        that.setData({
                            maintenanceData: data
                        })
                        return true;
                        break;
                    case "order_status_exit":
                        //监听订单取消
                        if (Number(data.status) === 8) {
                            that.setData({
                                isShow: true,
                                orderData: {}
                            })
                        }
                        return true;
                        break;
                }
            }
            if (wx.getStorageSync('token')) {
                that.getOrderInfo(function (res) {
                    console.log('sdfasdfs', that.data.orderData.id)
                })
            }
            const location = chooseLocation.getLocation();
            if (location) {
                if (that.data.isedit) {
                    that.setData({
                        // 起点的地点名称
                        startAddr: location.name ? location.name : "",
                        // 起点的详细地址
                        startXxAddr: location.address ? location.address : "",
                    })
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: location.latitude,
                            longitude: location.longitude
                        },
                        success: function (addressRes) {
                            const result = addressRes.result.formatted_addresses.recommend;
                            // that.setData({
                            // 	startAddr: result,
                            // })
                            const res = addressRes.result;
                            var myLocal = {
                                latitude: res.location.lat + '',
                                longitude: res.location.lng + '',
                                starAddr: location.name,
                                area_code: res.ad_info.adcode
                            }
                            wx.setStorageSync('myLocal', myLocal)
                            that.placeOrder('0')
                        }
                    })
                } else {
                    that.setData({
                        // 终点的地点名称
                        endAdr: location.name ? location.name : "",
                        // 终点的详细地址
                        endXxAdr: location.address ? location.address : "",
                        // 终点的经纬度信息
                        // 经度
                        endLat: location.latitude,
                        // 纬度
                        endLng: location.longitude,
                        //控制价格框的出现
                        isHas: true,
                    });
                    // 逆转录终点地经纬度信息，并储存
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: that.data.endLat,
                            longitude: that.data.endLng
                        },
                        success: function (addressRes) {
                            const result = addressRes.result.formatted_addresses.recommend;
                            const res = addressRes.result;
                            var finalLocal = {
                                latitude: that.data.endLat,
                                longitude: that.data.endLng,
                                endAddr: result,
                                area_code: res.ad_info.adcode
                            }
                            wx.setStorageSync('finalLocal', finalLocal)
                            that.placeOrder('0')
                        }
                    })
                }
            }
        } catch (e) {
            //TODO handle the exception
        }

    },
    getOrderInfo() {
        var that = this;
        var apis = api.api;
        var orderUrl = apis.host + 'userdjorder/curorder';
        var data = {};
        var userInfo = app.globalData.userAllInfo;
        that.setData({
            userInfo: userInfo,
        })
        apis.request(orderUrl, data, 'POST').then(function (res) {
            if (res.code == 200) {
                // 获取代驾信息
                if (JSON.stringify(res.data) === "{}") {
                    that.setData({
                        isShow: true //如果订单为空，则出现地图选点
                    })
                } else {
                    let url = apis.host + 'sys/userinfo';
                    let djData = {
                        id: res.data.dj_id
                    }
                    apis.request(url, djData, 'POST').then(function (res) {
                        if (res.code == 200) {
                            that.setData({
                                djName: res.data.username,
                                djMoblie: res.data.moblie,
                                djTx: res.data.avatar,
                            })
                        }
                    }).catch(function (res) {})
                    if (res.data.status <= 5 || Number(res.data.status) === 8) {
                        res.data.alltime = util.formatStoM(res.data.alltime)
                        if (res.data.sj_path) {
                            res.data.sj_path.juli = parseFloat(res.data.sj_path.juli).toFixed(2)
                        }
                        var nat = parseFloat(res.data.pre_price).toFixed(2);
                        if (res.data.status >= 5) {
                            nat = parseFloat(res.data.price).toFixed(2)
                        }
                        that.setData({
                            isShow: false,
                            orderData: res.data,
                            price: nat,
                            st_address: res.data.start_address,
                            e_address: res.data.address,
                            st_time: res.data.addtime.substr(-9, 6),
                        })
                    } else {
                        if (res.data.sj_path) {
                            res.data.sj_path.juli = parseFloat(res.data.sj_path.juli).toFixed(2)
                        }
                        res.data.alltime = util.formatStoM(res.data.alltime)
                        that.setData({
                            isShow: false,
                            orderData: res.data,
                            price: parseFloat(res.data.price).toFixed(2),
                            st_address: res.data.start_address,
                            e_address: res.data.address,
                            st_time: res.data.addtime.substr(-9, 6),
                        })
                    }
                }
            }
        }).catch(function (res) {
            that.setData({
                isShow: true
            })
        })
    },
    tabIcon() {
        var that = this
        if (that.data.isTop) {
            that.setData({
                isTop: false
            })
        } else {
            that.setData({
                isTop: true
            })
        }
    },
    confirm() {
        // http://dageda.api.hjdz.ltd/userdjorder/ordersure
        var that = this
        let apis = api.api;
        let url = apis.host + 'userdjorder/ordersure';
        let data = {
            id: that.data.orderId,
            /* 是 string 订单ID */
        };
        wx.showModal({
            title: '提示',
            content: '确定已到达目的地？',
            success: function (res) {
                if (res.confirm) {
                    apis.request(url, data, 'POST').then(function (res) {}).catch(function (res) {})
                } else {}
            }
        })
    },
    cancels() {
        // 直接取消订单，不通知用户
        var that = this
        let apis = api.api;
        let url = apis.host + 'userdjorder/exitcurorder';
        let data = {
            id: that.data.orderData.id,
            /* 是 string 订单ID */
            type: 0,
            /* 是 string 是否强制取消订单 默认 0 0 否 1 是 某些状态下需要强制取消 */
        };
        apis.request(url, data, 'POST').then(function (res) {
            wx.showToast({
                title: '取消成功'
            })
            setTimeout(function () {
                that.setData({
                    isShow: true
                })
            }, 1500)
        }).catch(function (res) {})
    },
    cancel() {
        //取消订单
        // http://dageda.api.hjdz.ltd/userdjorder/exitcurorder
        var that = this
        let apis = api.api;
        let url = apis.host + 'userdjorder/exitcurorder';
        let data = {
            id: that.data.orderData.id,
            /* 是 string 订单ID */
            type: 0,
            /* 是 string 是否强制取消订单 默认 0 0 否 1 是 某些状态下需要强制取消 */
        };
        wx.showModal({
            title: '确定取消订单？',
            success(res) {
                if (res.confirm) {
                    apis.request(url, data, 'POST').then(function (res) {
                        wx.showToast({
                            title: '取消成功'
                        })
                        wx.removeStorage({
                            key: 'order_time_' + wx.getStorageSync('userAllInfo').id
                        })
                        setTimeout(function () {
                            that.setData({
                                isShow: true
                            })
                        }, 1500)
                    }).catch(function (res) {})
                } else if (res.cancel) {}
            },
            fail(res) {
                wx.showToast({
                    title: '取消失败',
                    icon: 'none'
                })
            }
        })
    },
    placeOrder(type) {
        // 下单
        let that = this
        // let time = util.formatTime(new Date())
        let time = Date.now()
        let apis = api.api;
        let data = {
            address: wx.getStorageSync('myLocal').longitude + ',' + wx.getStorageSync('myLocal')
                .latitude, //是	string	出发地坐标
            addressname: that.data.startAddr, //是	string	出发地地址
            code: wx.getStorageSync('myLocal').area_code, //是	string	出发地城市代码
            to: wx.getStorageSync('finalLocal').longitude + ',' + wx.getStorageSync('finalLocal')
                .latitude, //是	string	目的地坐标
            toname: that.data.endAdr, //是	string	目的地地址
            tocode: wx.getStorageSync('finalLocal').area_code, //是	string	目的地城市代码
            carid: 0, //是	string	汽车ID
            starttime: time, //是	string	出发时间
            us_brief: '', //否	string	用户备注
            sure: type + '', //sure	否	string	默认为0 0预估订单信息 1下单
            trader_id: app.getTraderId(), // string,商家id,0代表没有,有的情况下就是商家的id,是用户通过扫码进入获取到的
            dj_id: app.getGetOrderData()
        };
        let url = apis.host + "userdjorder/index";
        wx.showLoading({
            title: '加载数据中',
        })
        if (that.data.startAddr !== '') {
            if (type == '0') {
                if (wx.getStorageSync('token')) {
                    if (wx.getStorageSync('finalLocal')) {
                        apis.request(url, data, 'POST').then(function (res) {
                            if (res.code == 200) {
                                that.setData({
                                    orderId: res.data.id,
                                    forecastPri: res.data.pre_price.toFixed(2),
                                })
                                wx.hideLoading()
                                chooseLocation.setLocation(null);
                            } else {}
                        }).catch(function (res) {
                            wx.hideLoading()
                        })
                    } else {
                        wx.hideLoading()
                    }
                } else {
                    wx.hideLoading()
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            } else {
                if (wx.getStorageSync('token')) {
                    apis.request(url, data, 'POST').then(function (res) {
                        if (res.code == 200) {
                            wx.setStorageSync('isClose', false)
                            var djid = wx.getStorageSync('scene_djId')
                            if (djid) {
                                app.getUserInfo(djid, function (sceneRes) {
                                    if (sceneRes) {
                                        wx.removeStorage({
                                            key: 'scene_djId'
                                        })
                                        that.setData({
                                            djName: sceneRes.username,
                                            djMoblie: sceneRes.moblie,
                                            djTx: sceneRes.avatar,
                                            orderId: res.data.id,
                                            price: res.data.pre_price.toFixed(2),
                                            st_address: res.data.start_address,
                                            e_address: res.data.address,
                                            st_time: res.data.addtime.substr(-9, 6),
                                            orderData: res.data
                                        })
                                    }
                                })
                            } else {
                                that.countDownTime()
                                that.countDown()
                                that.setData({
                                    orderId: res.data.id,
                                    price: res.data.pre_price.toFixed(2),
                                    st_address: res.data.start_address,
                                    e_address: res.data.address,
                                    st_time: res.data.addtime.substr(-9, 6),
                                    orderData: res.data
                                })
                            }
                            wx.showToast({
                                title: '呼叫代驾成功！',
                                icon: 'success',
                                duration: 2000
                            })
                            //开始倒计时5分钟
                            // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
                            chooseLocation.setLocation(null);
                            setTimeout(function () {
                                that.setData({
                                    isShow: false,
                                    endAdr: '',
                                    forecastPri: 0
                                })
                                // that.setCountDown()
                                // wx.navigateTo({
                                // 	url: '/pages/index/index',
                                // })
                            }, 2000)
                        } else if (res.code == 199) {
                            wx.showToast({
                                title: '您已更换登录设备，请重新登录!',
                                icon: 'error',
                                duration: 2000
                            })
                            setTimeout(function () {
                                wx.navigateTo({
                                    url: '/pages/login/login',
                                })
                            }, 1500)
                        } else {
                            let msg = res.msg
                            wx.showToast({
                                title: msg,
                                icon: 'none',
                                duration: 2500
                            })
                        }
                    }).catch(function (res) {
                        wx.showToast({
                            title: '呼叫代驾失败',
                            icon: 'error',
                            duration: 3000
                        })
                    })
                }
            }
        }
    },
    scanEvent() {
        //打开扫一扫
        var that = this;
        app.commonScan(function (res) {
            app.commonInit(res);
        })
    },
    getDjData(callback) {
        //获取代驾信息
        var that = this;
        let apis = api.api;
        let url = apis.host + 'user/getuser';
        if (wx.getStorageSync('scene_djId')) {

        }
        let data = {};
        apis.request(url, data, 'POST').then(function (res) {
            if (res.code == 200) {
                callback(res)
            }
        }).catch(function (res) {
            // console.log('获取失败', res)
        })
    },
    getData() {
        var that = this;
        let apis = api.api;
        let url = apis.host + 'user/getuser';
        let data = {};
        if (wx.getStorageSync('token')) {
            apis.request(url, data, 'POST').then(function (res) {
                if (res.code == 200) {
                    apis.setUserInfo(res.data)
                    app.globalData.userAllInfo = res.data;
                }
            }).catch(function (res) {
                // console.log('获取失败', res)
            })
        }
        // 初始化腾讯位置服务
        // qqmapsdk = new QQMapWX({
        // 	key: 'U5VBZ-N54W3-TOW3X-YOB2G-LHJGT-G6FC5'
        // });
        var that = this;
        wx.showLoading({
            title: '正在加载中'
        })
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    markers: [{
                        id: 1,
                        latitude: res.latitude,
                        /* 纬度	number	是	浮点数，范围 -90 ~ 90 */
                        longitude: res.longitude,
                        /* 经度	number	是	浮点数，范围 -180 ~ 180 */
                        callout: {
                            bgColor: '#fff',
                            display: 'ALWAYS',
                            borderRadius: 5,
                            padding: 2,
                        },
                    }],
                });
                var nowLocation = {
                    lng: res.longitude,
                    lat: res.latitude
                };
                wx.setStorageSync('nowLocat', nowLocation)
                that.getPoiList(res.longitude, res.latitude)
                that.getdriverlist(res.longitude, res.latitude)
                // 逆转录经纬度得到具体地理位置
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: function (addressRes) {
                        const result = addressRes.result.formatted_addresses.recommend;
                        that.setData({
                            startAddr: result,
                        })
                        wx.hideLoading()
                        var myLocal = {
                            latitude: res.latitude + '',
                            longitude: res.longitude + '',
                            starAddr: result,
                            area_code: addressRes.result.ad_info.adcode
                        }
                        wx.setStorageSync('myLocal', myLocal)
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: "定位失败，请重试",
                            icon: "none"
                        })
                        wx.hideLoading()
                    },
                    complete: function () {}
                })
            },
            fail: function (err) {
                that.setData({
                    show: true
                })
                setTimeout(function (err) {
                    that.setData({
                        show: false
                    })
                    wx.showModal({
                        title: '提示',
                        content: '请重新进入小程序'
                    })
                }, 10000)
            }
        })
    },
    onLoad(options) {
        var that = this;
        that.getData();
        that.setData({
            height: app.globalData.customBar
        })
        wx.login({
            success(res) {
                if (res.code) {
                    let apis = api.api;
                    let url = apis.host + "user/wechat_login";
                    let data = {
                        code: res.code
                    };
                    apis.request(url, data, "POST").then(function (res) {
                        if (res.code === 200) {
                            if (res.data.token) {
                                wx.setStorageSync('token', res.data
                                    .token)
                                // app.globalData.isLogin = true;
                                wx.setStorageSync('isLogin', true)
                                // that.setData({
                                // })
                                that.getOrderInfo()
                                that.setData({
                                    isLogin: true
                                })
                            } else {
                                // console.log('获取token失败', res.data.token)
                            }
                            app.initUser();
                        }
                        var opt = Object.keys(options)
                        if (opt.length != 0) {
                            const scene = decodeURIComponent(options.scene)
                            app.getScene(scene, function (res) {
                                try {
                                    res.content = JSON.parse(res.content);
                                } catch (e) {
                                    //TODO handle the exception
                                    res.content = res.content
                                }
                                let arr = res.url.split('/');
                                let typemore = arr[arr.length - 1];
                                let typearr = typemore.split('.');
                                let type = typearr[0];
                                app.commonInit({
                                    t: type,
                                    data: res
                                })
                            });
                            // console.log('scene', scene)
                        }
                    }).catch(function (res) {
                        var opt = Object.keys(options)
                        if (opt.length != 0) {
                            const scene = decodeURIComponent(options.scene)
                            app.getScene(scene, function (res) {
                                try {
                                    res.content = JSON.parse(res.content);
                                } catch (e) {
                                    //TODO handle the exception
                                    res.content = res.content
                                }
                                let arr = res.url.split('/');
                                let typemore = arr[arr.length - 1];
                                let typearr = typemore.split('.');
                                let type = typearr[0];
                                app.commonInit({
                                    t: type,
                                    data: res
                                })
                            });
                            // console.log('scene', scene)
                        }
                    })
                }
            },
            fail: function (res) {

            }
        })
        // sockets.onPageMessage = function(res) {}
    },
    onUnload() {
        // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
        chooseLocation.setLocation(null);
    },
    goMy() {
        wx.navigateTo({
            url: '/pages/personal/personal',
        })
    },
    // 页面销毁
    // onUnload() {
    // 	clearInterval(timeId);
    // },
    //显示地图
    showMap(e) {
        var that = this
        //使用在腾讯位置服务申请的key（必填）
        const key = "U5VBZ-N54W3-TOW3X-YOB2G-LHJGT-G6FC5";
        //调用插件的app的名称（必填）
        const referer = "大哥大代驾";
        const location = JSON.stringify({
            // lat: wx.getStorageSync('myLocal').latitude,
            // /* 是	string	经度 */
            // lng: wx.getStorageSync('myLocal').longitude,
            latitude: wx.getStorageSync('myLocal').latitude,
            longitude: wx.getStorageSync('myLocal').longitude
        });
        if (e.currentTarget.dataset.type === 'start') {
            that.data.isedit = true
        } else {
            that.data.isedit = false
        }
        wx.navigateTo({
            url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer +
                '&location=' + location
        });
    },
    /**
     * 获取中间点的经纬度，并mark出来
     */
    getdriverlist(lng = this.data.longitude, lat = this.data.longitude) {
        const that = this;
        let apis = api.api;
        let url = apis.host + '/userdjorder/fujinOrder';
        let data = {
            address: that.data.longitude + ',' + that.data.latitude
        };
        if (wx.getStorageSync('token')) {
            apis.request(url, data, 'POST').then(function (res) {
                // console.log('success')
                // address: "113.036249,23.005185"
                // juli: 0
                // userid: 2
                var data = res.data;
                for (var i = 0; i < data.length; i++) {
                    data[i].address = data[i].address.split(',')
                    data[i].lng = data[i].address[0]
                    data[i].lat = data[i].address[1]
                    var lng = data[i].lng
                    var lat = data[i].lat
                    var index = "markers[" + (i + 1) + "]";
                    that.setData({
                        [index]: {
                            id: data[i].userid,
                            iconPath: 'https://cdn.oss.dgddaijia.com/icons/dgd_sm.png',
                            width: 20,
                            /* 标注图标宽度	number/string	否	默认为图片实际宽度 */
                            height: 20,
                            /* 标注图标高度	number/string	否	默认为图片实际高度 */
                            latitude: data[i].lat,
                            /* 纬度	number	是	浮点数，范围 -90 ~ 90 */
                            longitude: data[i].lng,
                            /* 经度	number	是	浮点数，范围 -180 ~ 180 */
                            callout: {
                                bgColor: '#2F3451',
                                display: 'ALWAYS',
                                color: '#fff',
                                borderRadius: 5,
                                padding: 10,
                                content: "司机的距离:" + data[i].juli + "KM"
                            },
                        }
                    })
                }
            })
        }
    },
    /**
     * 视野发生变化时触发：见页面bindregionchange事件
     */
    regionchange(e) {
        e.type == 'end' ? this.getLngLat() : this.getLngLat()
    },
    /**
     * 详情见官方API配置:http://lbs.qq.com/qqmap_wx_jssdk/method-reverseGeocoder.html
     */
    getPoiList(longitude, latitude) {
        let that = this
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude,
            },
            get_poi: 1,
            poi_options: 'policy=2;radius=3000;page_size=2;page_index=1',
            success: function (res) {
                /**
                 * 详细数据从这儿拿....
                 */
                that.setData({
                    startaddr: res.result.pois[0].title
                });
            },
            fail: function (res) {},
            complete: function (res) {

            }
        });
    },
    // 获取经纬度
    getLngLat() {
        const that = this;
        that.mapCtx = wx.createMapContext("map");
        that.mapCtx.getCenterLocation({
            success: function (res) {
                that.setData({
                    longitude: res.longitude,
                    latitude: res.latitude
                })
                that.getPoiList(res.longitude, res.latitude)
                that.getdriverlist(res.longitude, res.latitude)

            }
        })
    },
    // 刷新地点
    refreshloction() {
        this.mapCtx.moveToLocation();
    },
    callDj: function () {
        const that = this;
        if (that.data.endAdr == '') {
            wx.showToast({
                title: '请先选择终点',
                icon: 'none'
            })
        } else {
            // console.log(wx.getStorageSync('token'), typeof wx.getStorageSync('token'))
            if (!wx.getStorageSync('token')) {
                wx.showToast({
                    title: '请先登录!',
                    icon: 'error',
                    duration: 2000
                })
                setTimeout(function () {
                    wx.navigateTo({
                        url: '/pages/login/login',
                    })
                }, 1500)
            } else {
                const that = this;
                // console.log('出发点', that.data.startAddr, '目的地', that.data.endAdr)
                that.placeOrder('1')
            }
        }
    },
    bindGetUserInfo: function (e) {
        if (e.detail.userInfo) {
            //用户按了允许授权按钮
            var that = this;
            // 获取到用户的信息了，打印到控制台上看下
            app.globalData.userInfo = e.detail.userInfo;
            //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
            that.setData({
                isHide: false
            });
        } else {
            //用户按了拒绝按钮
            wx.showModal({
                title: '警告',
                content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
                showCancel: false,
                confirmText: '返回授权',
                success: function (res) {
                    // 用户没有授权成功，不需要改变 isHide 的值
                    if (res.confirm) {
                        // console.log('用户点击了“返回授权”');
                    }
                }
            });
        }
    }
})